import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';

// class MyApp extends StatelessWidget {
//   const MyApp({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       title: '文档预览',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         visualDensity: VisualDensity.adaptivePlatformDensity,
//       ),
//       home: DocumentPreviewPage(
//         fileUrl: 'https://example.com/sample.pdf',
//         fileName: '示例文档.pdf',
//         fileType: 'pdf',
//       ),
//     );
//   }
// }

class DocumentPreviewPage extends StatefulWidget {
  final String fileUrl;
  final String fileName;
  final String fileType;

  const DocumentPreviewPage({
    super.key,
    required this.fileUrl,
    required this.fileName,
    required this.fileType,
  });

  @override
  State<DocumentPreviewPage> createState() => _DocumentPreviewPageState();
}

class _DocumentPreviewPageState extends State<DocumentPreviewPage> {
  late final WebViewController _webViewController;
  final Dio _dio = Dio();
  double _downloadProgress = 0.0;
  bool _isLocalFile = false;

  @override
  void initState() {
    super.initState();
    _checkFileType();
    if (widget.fileType.toLowerCase() == 'doc' ||
        widget.fileType.toLowerCase() == 'docx' ||
        widget.fileType.toLowerCase() == 'xls' ||
        widget.fileType.toLowerCase() == 'xlsx') {
      _initWebView();
    }
  }

  void _initWebView() {
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse(
          'https://docs.google.com/gview?embedded=true&url=${widget.fileUrl}'));
  }

  void _checkFileType() {
    setState(() {
      _isLocalFile = widget.fileUrl.startsWith('file://');
    });
  }

  Future<void> _downloadFile() async {
    final status = await Permission.storage.request();
    if (!status.isGranted) return;

    try {
      final dir = await getApplicationDocumentsDirectory();
      final savePath = '${dir.path}/${widget.fileName}';

      await _dio.download(
        widget.fileUrl,
        savePath,
        onReceiveProgress: (received, total) {
          setState(() {
            _downloadProgress = received / total;
          });
        },
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('文件已保存到：$savePath')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('下载失败：$e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _downloadProgress = 0.0);
      }
    }
  }

  Future<void> _shareFile() async {
    if (_isLocalFile) {
      final path = widget.fileUrl.replaceFirst('file://', '');
      await Share.shareXFiles([XFile(path)], text: '分享文件');
    } else {
      await Share.share(widget.fileUrl, subject: '文件分享');
    }
  }

  Widget _buildPreviewContent() {
    final fileType = widget.fileType.toLowerCase();

    switch (fileType) {
      case 'pdf':
        return SfPdfViewer.network(widget.fileUrl);
      case 'txt':
        return FutureBuilder<String>(
          future: _dio.get(widget.fileUrl).then((res) => res.data),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: SelectableText(
                  snapshot.data!,
                  style: const TextStyle(fontSize: 16),
                ),
              );
            }
            return const Center(child: CircularProgressIndicator());
          },
        );
      default:
        return WebViewWidget(controller: _webViewController);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(widget.fileName, style: const TextStyle(fontSize: 16)),
            Text(
              _getFileTypeText(),
              style: const TextStyle(fontSize: 12),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.download),
            onPressed: _downloadFile,
          ),
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _shareFile,
          ),
        ],
      ),
      body: Stack(
        children: [
          _buildPreviewContent(),
          if (_downloadProgress > 0)
            LinearProgressIndicator(
              value: _downloadProgress,
              backgroundColor: Colors.grey[200],
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
            ),
        ],
      ),
    );
  }

  String _getFileTypeText() {
    switch (widget.fileType.toLowerCase()) {
      case 'pdf':
        return 'PDF文档';
      case 'doc':
      case 'docx':
        return 'Word文档';
      case 'xls':
      case 'xlsx':
        return 'Excel文档';
      case 'txt':
        return '文本文件';
      default:
        return '未知格式';
    }
  }
}
